package project3.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import project3.annotation.Constrain;
import project3.annotation.Table;
import project3.annotation.Type;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CreateTable {
	public static int keyCount = 0;
	public static void create(Class clazz){
		Annotation TabAnno = clazz.getAnnotation(Table.class);
		if(TabAnno == null){ // 注解不存在
			System.out.println("注解不存在");
			return;
		}
		if(!(TabAnno instanceof Table)){ // 注解不是Table类型
			System.out.println("注解不是Table类型");
		}
		
		// 获取类名
		String TableName = clazz.getSimpleName(); // 获取表名****************
		
		Field[] fields = clazz.getDeclaredFields(); // 获取每个字段
		if(fields.length == 0){ // 字段为空
			System.out.println("字段为空");
			return;
		}
		List<String> attrNames = new ArrayList<>(); // 字段名数组****************
		List<String> attrTypes = new ArrayList<>(); // 字段类型数组****************
		List<String> attrConstrain = new ArrayList<>(); // 字段约束数组****************
		for(Field field : fields) {
			Annotation TypeAnno = field.getAnnotation(Type.class);
			if (TypeAnno != null) { // 注解存在
				attrNames.add(field.getName()); // 获取字段名****************
				attrTypes.add(field.getType().getSimpleName()); // 获取字段类型****************
				String Constraint = "";
				if (field.isAnnotationPresent(Constrain.class)) { // 字段有约束
					if (field.getAnnotation(Constrain.class).PrimaryKey()) { // 主键
						if (keyCount > 0) {
							System.out.println("主键只能有一个");
							return;
						}
						Constraint += "PRIMARY KEY";
						keyCount++;
					}
					if (field.getAnnotation(Constrain.class).NotNull()) { // 非空
						Constraint += "NOT NULL";
					}
					if (field.getAnnotation(Constrain.class).Unique()) { // 唯一
						Constraint += "UNIQUE";
					}
				}
				attrConstrain.add(Constraint); // 获取字段约束****************
			}
		}
		
		StringBuilder sql = new StringBuilder("CREATE TABLE " + TableName + "("); // 拼接SQL语句****************
		for (int i = 0; i < attrNames.size(); i++) {
			sql.append(attrNames.get(i)).append(" ");
			switch (attrTypes.get(i)) {
				case "String" -> sql.append("VARCHAR(255)");
				case "Integer" -> sql.append("INT");
				case "Double" -> sql.append("DOUBLE");
				case "Boolean" -> sql.append("BOOLEAN");
				case "Date" -> sql.append("DATE");
				case "Time" -> sql.append("TIME");
				case "Timestamp" -> sql.append("TIMESTAMP");
			}
			sql.append(" ");
			sql.append(attrConstrain.get(i));
			if (i < attrNames.size() - 1) {
				sql.append(", ");
			}
		}
		sql.append(");");
		System.out.println(sql);
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
		jdbcTemplate.execute(sql.toString());
	}
}
